from jinja2 import Environment, FileSystemLoader
from typing import Dict, Any
import os

class TemplateGenerator:
    """使用Jinja2模板生成Markdown"""
    
    def __init__(self, template_dir: str = "templates"):
        self.env = Environment(
            loader=FileSystemLoader(template_dir),
            trim_blocks=True,
            lstrip_blocks=True
        )
    
    def render_template(
        self,
        template_name: str,
        context: Dict[str, Any],
        output_path: str
    ) -> bool:
        """
        渲染模板并生成文件
        :param template_name: 模板文件名
        :param context: 模板变量字典
        :param output_path: 输出路径
        """
        try:
            template = self.env.get_template(template_name)
            rendered = template.render(**context)
            
            with open(output_path, 'w', encoding='utf-8') as f:
                f.write(rendered)
            return True
        except Exception as e:
            print(f"模板渲染失败: {e}")
            return False

# 示例模板 (templates/report_template.md)
"""
# {{ title }} - 分析报告
生成时间: {{ generation_time }}

## 数据概览
- 记录总数: {{ total_records }}
- 特征数量: {{ total_features }}

{% if summary_table %}
## 统计摘要
{{ summary_table }}
{% endif %}

{% if notes %}
## 注意事项
{% for note in notes %}
- {{ note }}
{% endfor %}
{% endif %}
"""